﻿using System;
using System.Collections.Generic;
using System.Linq;
using Library.Web.Models;
using Library.Web.Infrastructure;
using System.ComponentModel;
using Library.Web.Data;

namespace Library.Web.ViewModels
{
    public class BookViewModel : BaseViewModel
    {

        #region properties

        [DisplayName("Authors name")]
        public string AuthorNames { get; set; }

        [DisplayName("Book Title")]
        public string Title { get; set; }

        [DisplayName("Loan")]
        public bool IsLoan { get; set; }

        [DisplayName("Categories:")]
        public Infrastructure.CheckboxList BookCategories { get; set; }

        public PagedList<Data.Book> BookSearchResult { get; private set; }

        #endregion

        public BookViewModel()
        {
            FetchCategories();
        }

        /// <summary>
        /// Get books paged
        /// </summary>
        /// <param name="page"></param>
        public void GetBookPage(int page)
        {
            var books = Repository.Books;

            // Authors
            if (!string.IsNullOrEmpty(AuthorNames))
            {
                foreach (var author in AuthorNames.Split(new string[] { "," }, StringSplitOptions.None))
                {
                    books = books.Where(b => b.Authors.Contains(author));
                }
            }

            // Loan flag
            // books = books.Where(b => b.IsLoaned == IsLoan);

            // Book title
            if (!string.IsNullOrEmpty(Title))
            {
                books = books.Where(b => b.Title.Contains(Title));
            }

            // categories
            var selectedCategories = BookCategories
                .Where(i => i.IsChecked == true)
                .Select(i => i.Value);

            if (selectedCategories.Count() > 0)
            {
                books = books.Where(b => b.BookCategories.Any(cb => selectedCategories.Contains(cb.CategoryId)));
            }
            
            BookSearchResult = new PagedList<Data.Book>(books, page);
        }

        /// <summary>
        /// Retrive categories from DB
        /// </summary>
        private void FetchCategories()
        {
            var bookCateges = Repository.Categories.ToList()
                .Select(c => new CheckboxListItem { Desciption = c.Description, Value = c.Id })
                .ToList();

            BookCategories = new CheckboxList();
            BookCategories.AddRange(bookCateges);
        }


    }
}